package com.bdqn.crm.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.crm.pojo.BasDict;
import com.bdqn.crm.pojo.SysRight;
import com.bdqn.crm.pojo.SysRole;
import com.bdqn.crm.service.SysRightService;
import com.bdqn.crm.service.SysRoleService;
import com.bdqn.crm.utils.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("role")
public class RoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRightService sysRightService;


    @RequestMapping("list")
    public String list(HttpServletRequest request, Model model, @RequestParam(value = "roleName",required = false) String roleName, @RequestParam(required = false, defaultValue = "1") int pageIndex){
        Page<SysRole> page = new Page<>(pageIndex, 5);
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        //判断是否有查询条件
        if (roleName != null) {
            queryWrapper.like("role_name", roleName);      //模糊设置条件
        }

        if (sysRoleService.count(queryWrapper) == 0) {     //此操作说明 数据库没有数据可展示，那么就全部清零
            page.setTotalElements(0);
            page.setContent(null);
        } else {
            page.setTotalElements(sysRoleService.count(queryWrapper));
            page.setContent(sysRoleService.selectPages(roleName,(page.getNumber() - 1) * page.getPageSize(), page.getPageSize()));
        }

        //权限
        List<SysRight> rights = sysRightService.list();

        model.addAttribute("roleName",roleName);

        model.addAttribute("rolePage", page);
        return "role/list";
    }

    @RequestMapping("add")
    public String toAdd(Model model){
        //权限
        List<SysRight> rights = sysRightService.list();
        model.addAttribute("rights",rights);
        return "role/add";
    }

    @RequestMapping("save")
    public String save(SysRole role,HttpServletRequest request,String[] rightCodes){
        for (String rightCode : rightCodes) {
            SysRight sysRight = new SysRight();
            sysRight.setRightCode(rightCode);
            role.getRights().add(sysRight);
        }

        return "redirect:/role/list";
    }

}
